import { computed } from 'vue';
import { useCountDown, useLoading } from '@sa/hooks';
import { REG_PHONE } from '@/constants/reg';
import { $t } from '@/locales';

export function useCaptcha(initialWaitSeconds = 60) {
  const { loading, startLoading, endLoading } = useLoading();
  const { count, start, stop, isCounting } = useCountDown(initialWaitSeconds);

  const label = computed(() => {
    let text = $t('page.login.codeLogin.getCode');

    const countingLabel = $t('page.login.codeLogin.reGetCode', { time: count.value });

    if (loading.value) {
      text = '';
    }

    if (isCounting.value) {
      text = countingLabel;
    }

    return text;
  });

  function isAccountValid(account: string, type: 'phone' | 'email') {
    if (account.trim() === '') {
      window.$message?.error?.(type === 'phone' ? $t('form.phone.required') : $t('form.email.required'));

      return false;
    }

    if (type === 'phone') {
      if (!REG_PHONE.test(account)) {
        window.$message?.error?.($t('form.phone.invalid'));
        return false;
      }
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(account)) {
      // 简单的邮箱格式验证
      window.$message?.error?.($t('form.email.invalid'));
      return false;
    }

    return true;
  }

  async function getCaptcha(account: string, options?: { type?: 'phone' | 'email'; waitSeconds?: number }) {
    const type = options?.type || 'phone';
    const waitSeconds = options?.waitSeconds || initialWaitSeconds;
    const valid = isAccountValid(account, type);

    if (!valid || loading.value) {
      return;
    }

    startLoading();

    // 如果waitSeconds参数与当前倒计时时间不同，更新倒计时时间
    if (waitSeconds !== initialWaitSeconds) {
      // 重置倒计时组件的时间
      stop();
      // 这里需要重新创建倒计时实例或修改现有实例的时间
      // 由于useCountDown可能不支持动态修改时间，我们可以直接使用传入的waitSeconds时间
    }

    // request
    await new Promise(resolve => {
      setTimeout(resolve, 500);
    });

    window.$message?.success?.($t('page.login.codeLogin.sendCodeSuccess'));

    start();

    endLoading();
  }

  return {
    label,
    start,
    stop,
    isCounting,
    loading,
    getCaptcha
  };
}
